package com.kly.order.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.fqgj.common.api.Page;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.kly.dto.Benefit;
import com.kly.dto.MemberDto;
import com.kly.enums.Benefits;
import com.kly.order.ServiceUtils;
import com.kly.order.db.dao.BenefitsDao;
import com.kly.order.db.dao.MemberDao;
import com.kly.order.db.dao.UserVasPurchasesDao;
import com.kly.order.db.entity.BenefitsEntity;
import com.kly.order.db.entity.MemberEntity;
import com.kly.order.db.entity.UserVasPurchasesEntity;
import com.kly.service.MemberService;
import com.kly.user.dto.UserCodeDto;
import com.kly.user.dto.UserInfoDto;
import com.kly.user.service.AuthLoginService;
import com.kly.user.service.UserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 权益发放定时任务
 * @author linqu
 */
@Component
public class GenerateBenefitTask {

    private static Log logger = LogFactory.getLog(GenerateBenefitTask.class);
    @Resource
    private UserService userService;
    @Resource
    UserVasPurchasesDao userVasPurchasesDao;
    @Resource
    MemberDao memberDao;
    @Resource
    AuthLoginService authLoginService;



    /**
     * 每天0点1秒执行权益分配，
     * 1点钟为补偿任务
     */
    @Scheduled(cron = "1 0 0,1 * * ?")
    public void execute() {


        logger.info("=============GenerateBenefitTask Start==================");
//        final int totalNum = getUserVasPurchasesTotal();
//        if (totalNum == 0) {
//            return;
//        }
//
//        final Page page = new Page(500, 1, totalNum);
//        for (int currentPage = 1; currentPage <= page.getTotalPageNum(); currentPage++) {
//            taskJob(page);
//            page.setCurrentPage(currentPage);
//        }

        final int hasUpdateBenefitNum = userVasPurchasesDao.updateAllUserBenefits();
        logger.info("=============首页浏览、Like权益发放============= , num:{}", hasUpdateBenefitNum);

//        final int hasUpdateBenefitNum2 = userVasPurchasesDao.updateFlashChatAndWlmBenefits();
//        logger.info("=============PP flashchat/wlm 权益按周发放============= , num:{}", hasUpdateBenefitNum2);


    }

//    private void taskJob(Page page) {
//        final List<UserVasPurchasesEntity> userVasPurchases = getUserVasPurchasesEntities(page);
//        for (UserVasPurchasesEntity userPurchases : userVasPurchases) {
//
//            if (userPurchases.getUserCode().equals("1693942575923298304")) {
//                System.out.println(userPurchases.getAdditionalBenefitCount());
//            }
//
//            // 用户状态检查
//            UserCodeDto userCodeDto = getUserCodeDto(userPurchases);
//            // 已删除用户需要清理权益表记录
//            if (Objects.isNull(userCodeDto)) {
//                userPurchases.setDeleted(Boolean.TRUE);
//                userVasPurchasesDao.updateByPrimaryKey(userPurchases);
//                continue;
//            }
//
//            // 会员权益发放
//            if (isMember(userPurchases.getUserCode())) {
//                  // 会员权利用户注册的时候就已经发放过
////                if (Benefits.FLASH_CHAT.getBenefitCode() == userPurchases.getBenefitCode()) {
////                    updateUserPurchase(userPurchases, 2, DateUtil.offsetDay(new Date(), 7));
////                } else if (Benefits.VIEW_PRIVATE_PHOTOS.getBenefitCode() == userPurchases.getBenefitCode()) {
////                    updateUserPurchase(userPurchases, 2, DateUtil.offsetDay(new Date(), 7));
////                } else if (Benefits.VIEW_PRIVATE_VIDEOS.getBenefitCode() == userPurchases.getBenefitCode()) {
////                    updateUserPurchase(userPurchases, 2, DateUtil.offsetDay(new Date(), 7));
////                }
//            }
//
//            // 非会员权益发放
//            else {
//
//                // 是否为首次注册用户
//                final Boolean isFirstRegister = authLoginService.firstRegister(userCodeDto.getClientId(),
//                        userCodeDto.getMobile(), userCodeDto.getEmail()).getData();
//
//
//                // 首页浏览次数发放
//                if (Benefits.NUMBER_OF_USERS_BROWSED.getBenefitCode() == userPurchases.getBenefitCode()) {
//                    if (isFirstRegister && isNewUser(userCodeDto)) {
//                        updateUserPurchase(userPurchases, 50, DateUtil.endOfDay(new Date()));
//                    } else {
//                        updateUserPurchase(userPurchases, 20, DateUtil.endOfDay(new Date()));
//                    }
//                }
//                // Like发放
//                else if (Benefits.NUMBER_OF_USERS_LIKED.getBenefitCode() == userPurchases.getBenefitCode()) {
//                    if (isFirstRegister && isNewUser(userCodeDto)) {
//                        updateUserPurchase(userPurchases, 20, DateUtil.endOfDay(new Date()));
//                    } else {
//                        updateUserPurchase(userPurchases, 5, DateUtil.endOfDay(new Date()));
//                    }
//                }
//                // 破冰会话发放
//                else if (Benefits.ICE_BREAKING_SESSION.getBenefitCode() == userPurchases.getBenefitCode()) {
//                    if (isFirstRegister && isNewUser(userCodeDto)) {
//                        updateUserPurchase(userPurchases, 3, DateUtil.endOfDay(new Date()));
//                    } else {
//                        updateUserPurchase(userPurchases, 2, DateUtil.endOfDay(new Date()));
//                    }
//                }
//            }
//        }
//
//
//        logger.info("=================GenerateBenefitTask End==============");
//    }

    private Boolean isNewUser(UserCodeDto userCodeDto) {
        return userCodeDto.getGmtCreate().after(DateUtil.beginOfDay(new Date()));
    }

    public static void main(String[] args) {
        final DateTime dateTime = DateUtil.endOfDay(new Date());
        System.out.println(dateTime);
        System.out.println(DateUtil.beginOfDay(new Date()));

        final DateTime dateTime1 = DateUtil.parseDateTime("2023-08-18 00:00:01");
        System.out.println(dateTime.after(dateTime1));

        final Page page = new Page(500, 1, 31776);

        System.out.println(page.getTotalPageNum());


        for (int currentPage = 1; currentPage <= page.getTotalPageNum(); currentPage++) {
            page.setCurrentPage(currentPage);
            System.out.println("currentPage:" + page.getCurrentPage());
            System.out.println(page.getStartIndex() );
            System.out.println(page.getEndIndex() );
        }


    }

    private void updateUserPurchase(UserVasPurchasesEntity userPurchases, Integer addiditionalNum, Date endDate) {
        userPurchases.setAdditionalBenefitCount(addiditionalNum);
        userPurchases.setAdditionalStartDate(new Date());
        userPurchases.setAdditionalEndDate(endDate);
        userPurchases.setUsageCount(0);
        userVasPurchasesDao.updateByPrimaryKey(userPurchases);
    }

    private UserCodeDto getUserCodeDto(UserVasPurchasesEntity userPurchases) {
        UserCodeDto userCodeDto = null;
        final Response<UserCodeDto> userCodeDtoResponse = userService.selectActiveUser(userPurchases.getUserCode());
        if (userCodeDtoResponse.isSuccess()) {
            userCodeDto = userCodeDtoResponse.getData();
        }
        return userCodeDto;
    }


    private List<UserVasPurchasesEntity> getUserVasPurchasesEntities(Page page) {
        return userVasPurchasesDao.queryBenefits(page);
    }

    private int getUserVasPurchasesTotal() {
        return userVasPurchasesDao.queryBenefitsTotal();
    }

    private Boolean isMember(String userCode) {

        Map<String, Object> map = new HashMap<>();
        map.put("userCode", userCode);
        map.put("deleted", 0);
        map.put("date", new Date());
        Integer result = memberDao.ifMember(map);
        return result > 0;
    }

}
